package HomeService

import (
	"context"
	"database/sql"
	"gdshop-font-api-go/app/entity"
	"gdshop-font-api-go/app/request/HomeReq"
	"gdshop-font-api-go/app/response/HomeResp"
	"gdshop-font-api-go/library/response"
	"gdshop-font-api-go/library/tools"
	toolsDb "gdshop-font-api-go/library/tools/db"
	toolsJwt "gdshop-font-api-go/library/tools/jwt"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"github.com/gogf/gf/util/grand"
	"time"
)

// 注册
func Register(ctx context.Context, parames *HomeReq.Register) *response.JsonResponse {
	// 判断验证码是否正确
	if !tools.VerifyVCode(parames.Mobile, parames.Vcode) {
		return response.FailByRequestMessage(nil, "验证码错误")
	}

	return doRegister(ctx, parames, "注册成功")
}

// 快速注册，一般用于短信登陆
func QuickRegister(ctx context.Context, parames *HomeReq.Register) *response.JsonResponse {
	return doRegister(ctx, parames, "登陆成功")
}

func doRegister(ctx context.Context, parames *HomeReq.Register, successMsg string) *response.JsonResponse {
	memberDb := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "member")
	memberModel := (*entity.Member)(nil)
	err := memberDb.Where(g.Map{
		"mobile": parames.Mobile,
	}).Struct(&memberModel)
	if err != nil && err != sql.ErrNoRows {
		// 有错误，并且不是数据为空的错误，则返回
		return response.FailByRequestMessage(nil, err.Error())
	}
	if memberModel != nil {
		return response.FailByRequestMessage(nil, "当前账号已存在")
	}

	passwordSalt := grand.Letters(10)
	// 账号不存在，写入数据
	memberModel = &entity.Member{
		Mobile:       parames.Mobile,
		Password:     tools.EncryptPassword(parames.Password, passwordSalt),
		PasswordSalt: passwordSalt,
		Realname:     "用户" + parames.Mobile[3:11],
		Nickname:     "用户" + parames.Mobile[3:11],
		Status:       1,
		CreateAt:     uint(time.Now().Unix()),
	}

	result, err := memberDb.Insert(memberModel)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	id, err := result.LastInsertId()
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	memberModel.Id = uint(id)

	resp := new(HomeResp.Login)
	if err := gconv.Struct(memberModel, resp); err != nil {
		return response.FailByRequestMessage(nil, "数据转换失败")
	}

	tokenString, err := toolsJwt.GenerateLoginToken(memberModel.Id, memberModel.Realname)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	resp.Token = tokenString

	return response.SuccessByRequestMessageData(nil, successMsg, resp)
}
